<template>
  <div class="mainos">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <el-form
          :inline="true"
          :rules="rules"
          :model="monitorForm"
          class="demo-form-inline marginTop0"
          ref="userListFrom"
          label-width="60px"
        >
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>录单</span>
            </div>
          </div>
          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0"><em></em>单据信息</div>
          </div>
          <div class="main_xq">
            <ul class="boxha">
              <li>
                采购单号：<span>{{ info.order_sn }}</span>
              </li>
              <li>
                采购方式：<span>{{ base.mode[info.mode] }}</span>
              </li>
              <li>
                采购员/供应商：<span>{{
                  info.mode == 1
                    ? base.buyer[info.buyer_id]
                    : base.supplier[info.supplier_id]
                }}</span>
              </li>
              <li>
                类型：<span>{{ base.type[info.type] }}</span>
              </li>
              <li>
                单据状态：<span>{{ base.status[info.status] }}</span>
              </li>
              <li>
                采购日期：<span>{{
                  parseTime(info.purchase_time, "{y}-{m}-{d}")
                }}</span>
              </li>
              <li>
                需采购品种：<span>{{ info.all }}</span>
              </li>
              <li>
                已采购品种：<span>{{ info.ed }}</span>
              </li>
            </ul>
          </div>
          <div class="main_tile boxdq marginTop15">
            <div class="main_tile_l marginLeft0"><em></em>商品详情</div>
          </div>
          <div class="main_white padding10 marginBottom10">
            <div class="main_white">
              <div class="mainor_sp boxha">
                <ul class="box">
                  <li class="box">
                    <span>商品名称： </span>
                    <el-input
                      v-model.trim="formsp.value"
                      ref="focusw2"
                      placeholder="商品名称"
                      clearable
                      class="wid240"
                      @keyup.enter.native="mainor_qr"
                    ></el-input>
                  </li>
                </ul>
                <div class="marginBottom10">
                  <el-button type="primary" @click="mainor_qr"
                    >置顶(回车)</el-button
                  >
                  <el-button
                    class="reset marginLeft5"
                    type="info"
                    @click="formsp.value = ''"
                    >重置</el-button
                  >
                </div>
              </div>
              <div class="main_table marginTop0">
                <el-table
                  ref="multipleTable"
                  :data="monitorForm.list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                >
                  <el-table-column label="序号">
                    <template slot-scope="scope">{{
                      scope.$index + 1
                    }}</template>
                  </el-table-column>
                  <el-table-column label="商品名称" prop="name" width="150">
                    <template slot-scope="scope"
                      >{{ scope.row.name }}【{{
                        scope.row.spu_name
                      }}】</template
                    >
                  </el-table-column>
                  <el-table-column label="单位" prop="unit" />
                  <el-table-column label="状态" prop="unit_name">
                    <template slot-scope="scope">{{
                      scope.row.status==0?'采购中':'采购完成'
                    }}</template>
                  </el-table-column>
                  <el-table-column
                    label="近一次采购价"
                    prop="purchase_price"
                    width="150"
                  />
                  <el-table-column
                    label="需采量"
                    prop="purchase_num"
                    class-name="main_hei"
                  />
                  <el-table-column
                    label="未采量"
                    prop="un_purchase_num"
                    class-name="main_hei"
                  />
                  <el-table-column
                    label="数量"
                    prop="num"
                    width="150"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'list.' + scope.$index + '.num'"
                        :rules="rules.num"
                        label-width="10px"
                        label=" "
                      >
                        <el-input
                          v-model.trim="scope.row.num"
                          placeholder="数量"
                          class="wid110"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单价"
                    prop="price"
                    width="150"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'list.' + scope.$index + '.price'"
                        :rules="rules.price"
                        label-width="10px"
                        label=" "
                      >
                        <el-input
                          v-model.trim="scope.row.price"
                          placeholder="单价"
                          class="wid110"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="小计"
                    prop="market_price"
                    width="150"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      {{
                        parseFloat(scope.row.num) * parseFloat(scope.row.price)
                          ? (
                              parseFloat(scope.row.num) *
                              parseFloat(scope.row.price)
                            ).toFixed(2)
                          : 0.0
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="备注"
                    prop="remark"
                    width="350"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        <el-input
                          v-model.trim="scope.row.remark"
                          placeholder="备注"
                          class="wid240"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0">
              <em></em>其他<span>（图片只能上传3张）</span>
            </div>
          </div>
          <div class="main_xq">
            <ul class="boxha ">
              <li
                class="main_w100 box marginTop15 marginBottom15"
                v-for="(other_list, index) in monitorForm.other_list"
                :key="index"
              >
                <p class="base_p">{{ index == 0 ? "其他费用：" : "" }}</p>
                <div class="box main_xqi" style="margin-top: -4px">
                  <el-input
                    v-model.trim="other_list.descr"
                    placeholder="描述"
                    clearable
                    class="wid240"
                  ></el-input>
                  <el-input
                    v-model.trim="other_list.money"
                    placeholder="金额"
                    clearable
                    class="wid140 marginLeft15"
                  ></el-input>
                  <div class="main_page_top" v-if="index == 0">
                    <svg
                      aria-hidden="true"
                      width="15"
                      height="15"
                      @click="plus"
                    >
                      <use xlink:href="#icon-commodity_plus" />
                    </svg>
                  </div>
                  <div class="main_page_top" style="margin-left: 8px" v-else>
                    <svg
                      aria-hidden="true"
                      width="22"
                      height="22"
                      @click="reduce(index)"
                    >
                      <use xlink:href="#icon-commodity_reduce" />
                    </svg>
                  </div>
                </div>
              </li>
              <li class="main_w100">
                合计：<span>{{ total }}</span>
              </li>
              <li class="main_w100 box marginTop20">
                备注：
                <div class="box main_xqi" style="margin-top: -4px">
                  <el-input
                    v-model.trim="monitorForm.form.remark"
                    placeholder="备注"
                    clearable
                    style="width: 60%"
                  ></el-input>
                </div>
              </li>
              <li class="main_w100 box marginTop20">
                收据、发票等凭证上传：
                <div class="box main_xqi">
                  <div class="main_upImg">
                    <el-upload
                      :action="uploadPath"
                      list-type="picture-card"
                      :on-success="handSuccess"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :limit="3"
                      :file-list="filelist"
                    >
                      <span slot="default">
                        <svg
                          aria-hidden="true"
                          class="main_page_svg"
                          width="32"
                          height="27"
                        >
                          <use xlink:href="#icon-commodit_camera" />
                        </svg>
                      </span>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img :src="dialogImageUrl" alt />
                    </el-dialog>
                    <div class="clearfix"></div>
                  </div>
                </div>
              </li>
            </ul>
          </div>

          <div class="newConBox_p200 paddingBottom10" id="newConBox">
            <div class="newConBox_h32">
              <div
                :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
              >
                <div class="mainor_prl">
                  <el-button
                    type="primary"
                    @click="preservation(1)"
                    v-repeatClick
                    >部分采购</el-button
                  >
                  <el-button v-repeatClick @click="preservation(2)"
                    >全部采购</el-button
                  >
                  <el-button @click="$router.back(-1)">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
const shuju = {
  other_list: {
    descr: "",
    money: "",
  },
};

import {
  purchase_info,
  purchase_base,
  purchase_entryList
} from "@/api/purchasing/purchasingPurchase";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/purchasing/purchasingPurchase_record";
import { parseTime } from "@/utils/index";
import { uploadPath } from "@/api/currency";

export default {
  computed: {
    total() {
      let sz = 0;
      let lz = 0;
      this.monitorForm.other_list.forEach((e) => {
        sz += parseFloat(e.money) ? parseFloat(e.money) : 0;
      });
      this.monitorForm.list.forEach((e) => {
        lz += parseFloat(e.num * e.price) ? parseFloat(e.num * e.price) : 0;
      });
      return (lz + sz + parseFloat(this.info.money))?(lz + sz + parseFloat(this.info.money)).toFixed(2):'0.00';
    },
  },
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 上传图片
      filelist: [],
      uploadPath,
      dialogImageUrl: "",
      dialogVisible: false,
      // 时间
      parseTime,
      // 基本信息
      info: {
        money:0,
        purchase_time: "2020-01-01",
      },
      base: {
        mode: ["自采"],
        buyer: ["自采"],
        supplier: ["自采"],
        type: ["自采"],
        status: ["自采"],
      },
      listLoading: false,
      // 列表数据
      monitorForm: {
        form: {
          status: 1,
          pics: [],
          remark: "",
        },
        list: [],
        other_list: [
          {
            descr: "",
            money: "",
          },
        ],
      },
      // 商品搜索
      formsp: {
        value: "",
      },
      // id
      id: this.$route.params.id,
      // 监听滚动
      searchBarFixed: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {
    // 基本信息
    this.purchase_info();
    this.purchase_base();
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 其他
    plus() {
      let other_list = JSON.parse(JSON.stringify(shuju.other_list));
      this.monitorForm.other_list.push(other_list);
    },
    reduce(index) {
      this.monitorForm.other_list.splice(index, 1);
    },
    // 置顶
    mainor_qr() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let list = JSON.parse(JSON.stringify(this.monitorForm.list));
      if (formsp.name != "") {
        list.map((e, index) => {
          if (e.name.includes(formsp.value)) {
            let sz = {};
            sz = e;
            list.splice(index, 1);
            list.unshift(sz);
          }
        });
        this.monitorForm.list = list;
      }
    },
    // 上传图片-删除
    handleRemove(file) {
      const i = this.monitorForm.form.pics.findIndex(
        (item) => item.path == file.path
      );
      this.monitorForm.form.pics.splice(i, 1);
    },
    // 上传图片-查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      // console.log(res, file, fileList);
      this.monitorForm.form.pics.push({
        name: "",
        path: res.path,
        url: res.src,
      });
    },
    // 删除
    scdelete(index, type) {
      this.monitorForm.list.splice(index, 1);
    },
    // 保存
    preservation(type) {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          let num = 0;
          let arry = [];
          let monitorForm = JSON.parse(JSON.stringify(this.monitorForm));
          monitorForm.list.map((e) => {
            if (parseFloat(e.num) > 0 && parseFloat(e.price) == 0) {
              num++;
            }
            if (parseFloat(e.num) == 0 && parseFloat(e.price) > 0) {
              num++;
            }
          });
          if (num > 0) {
            this.$message.error("请输入数量和单价大于0或者都不输入");
            return;
          }
          monitorForm.form.status = type;
          monitorForm.form.pics = monitorForm.form.pics
            .map((e) => e.path)
            .join(",");
          monitorForm.list.map((e) => {
            arry.push({
              remark: e.remark,
              num: e.num,
              price: e.price,
              id: e.id,
            });
          });
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            monitorForm.form,
            {
              list: JSON.stringify(arry),
              other_money: JSON.stringify(monitorForm.other_list),
              id: this.id,
            }
          );
          purchase_entryList(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.$router.go(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    // 基本信息
    purchase_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      purchase_info(data).then((res) => {
        if (res.errcode == 0) {
          res.data.info.purchase_list.map((e) => {
            e.price = "0.00";
            e.num = "0.00";
          });
          if(res.data.info.other_money){
            this.monitorForm.other_list=JSON.parse(res.data.info.other_money.split(","))
          }
          this.monitorForm.list = res.data.info.purchase_list;
          this.info = res.data.info;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    purchase_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      purchase_base(data).then((res) => {
        if (res.errcode == 0) {
          this.base = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainos {
  .main_tile {
    .mainos_tile_r {
      color: $colour_red;
      font-size: $font_14;
    }
  }
  .newConBox.on {
    margin-left: -10px;
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
  .main_xq {
    ul {
      li {
        .main_xqi {
          width: 80%;
          margin-left: 5px;
        }
        .main_upImg {
          /deep/ul {
            li {
              padding-left: 0;
            }
          }
          /deep/.el-upload-list--picture-card
            .el-upload-list__item:first-child {
            margin-left: 145px;
          }
        }
      }
    }
  }
  .mainor_sp {
    ul {
      margin-right: 20px;
      li {
        margin-bottom: 10px;
        & > span {
          display: inline-block;
          line-height: 32px;
          width: 60px;
          color: $colour_18;
          font-size: $font_14;
          text-align: right;
          em {
            color: $colour_red;
            margin-right: 5px;
          }
        }
        &:first-child {
          & > span {
            width: 85px;
          }
        }
      }
    }
  }
  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .base_p {
    width: 80px;
  }
  .main_page_top {
    margin-top: 7px;
    margin-left: 10px;
    use {
      fill: $menuText;
    }
    &:hover {
      cursor: pointer;
      use {
        fill: $menuActiveText;
      }
    }
  }
}
</style>
